<template>
  <view class="worker-settlement">
    <view class="step-container">
      <Step :stepList="stepList" :current="current" />
    </view>
    <view v-show="current == 1">
      <view class="form-container">
        <u--form
          :model="userInfo"
          :rules="rules"
          ref="uForm"
          labelWidth="180rpx"
        >
          <u-form-item prop="realName" label="姓名" class="input-name">
            <u--input
              v-model="userInfo.realName"
              placeholder="请输入姓名"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item prop="phone" label="手机号" class="input-name">
            <u--input
              v-model="userInfo.phone"
              placeholder="请输入手机号"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item
            prop="idCard"
            label="身份证号码"
            class="input-name last-name"
          >
            <u--input
              v-model="userInfo.idCard"
              placeholder="请输入身份证号码"
              border="none"
            ></u--input>
          </u-form-item>
        </u--form>
      </view>
      <view class="upload-container">
        <Upload
          :uploadWidth="'750rpx'"
          :uploadHeight="'480rpx'"
          @getUpLoadImage="getUpLoadSfz"
        >
          <view class="upload-file">
            <view
              class="upload-file-pic"
              :style="{
                width: '100%',
                height: '480rpx',
                background: `url(${sfzIcon}) no-repeat center`,
                backgroundSize: 'contain',
              }"
            >
              <u--image
                class="infor-image"
                :showLoading="true"
                :src="iconAdd"
                width="120rpx"
                height="120rpx"
              ></u--image>
              <view class="title">上传人像面</view>
            </view>
          </view>
        </Upload>
        <Upload
          :uploadWidth="'750rpx'"
          :uploadHeight="'480rpx'"
          @getUpLoadImage="getUpLoadSff"
        >
          <view class="upload-file">
            <view
              class="upload-file-pic"
              :style="{
                width: '100%',
                height: '480rpx',
                background: `url(${sffIcon}) no-repeat center`,
                backgroundSize: 'contain',
              }"
            >
              <u--image
                class="infor-image"
                :showLoading="true"
                :src="iconAdd"
                width="120rpx"
                height="120rpx"
              ></u--image>
              <view class="title">上传国徽面</view>
            </view>
          </view>
        </Upload>
      </view>
      <view class="next-step">
        <view class="btn" @click="nextStep(2)">下一步</view>
      </view>
    </view>
    <view v-show="current == 2">
      <view class="selection-service">
        <view class="service-list" @click="showCityPicker()">
          <view class="title">服务区域</view>
          <view class="select-list">
            {{ selectCityName ? selectCityName : "请选择" }}</view
          >
          <u-icon name="arrow-right" color="#CECECE" size="16"></u-icon>
        </view>
        <view class="service-list" @click="showCategoryPicker()">
          <view class="title">服务品类</view>
          <view class="select-list">
            {{ selectCategoryName ? selectCategoryName : "请选择" }}</view
          >
          <u-icon name="arrow-right" color="#CECECE" size="16"></u-icon>
        </view>
      </view>
      <view class="btn-container">
        <view class="btn-list">
          <view class="btn" @click="backStep(1)">上一步</view>
          <view class="btn" @click="nextStep(3)">下一步</view>
        </view>
      </view>
    </view>
    <view v-show="current == 3">
      <view v-if="isInReview">
        <view class="status-image">
          <u--image
            class="infor-image"
            :showLoading="true"
            :src="waitingReviewIcon"
            width="520rpx"
            height="320rpx"
          ></u--image>
          <view class="status">审核中...</view>
          <view class="tips">我们将尽快为您审核 请耐心等待...</view>
        </view>
        <view class="next-step">
          <view class="btn" @click="linkStaging()">确定</view>
        </view>
      </view>
      <view v-if="isAuditFailed">
        <view class="status-image">
          <u--image
            class="infor-image"
            :showLoading="true"
            :src="authenticationFailedIcon"
            width="520rpx"
            height="320rpx"
          ></u--image>
          <view class="status">审核失败...</view>
          <view class="tips">失败原因：{{ rejectReason }}</view>
        </view>
        <view class="next-step">
          <view class="btn" @click="reApply()">再次申请</view>
        </view>
      </view>
    </view>
    <view v-show="current == 4">
      <view v-if="true">
        <view class="status-image">
          <u--image
            class="infor-image"
            :showLoading="true"
            :src="certificationSuccessfulIcon"
            width="520rpx"
            height="320rpx"
          ></u--image>
          <view class="status">认证成功</view>
          <view class="tips"
            >您已通过认证正式成为鲁班师傅，快去抢单赚钱吧~</view
          >
        </view>
      </view>
      <view class="next-step">
        <view class="btn" @click="immediateOrder()">立即抢单</view>
      </view>
    </view>
    <TreePicker
      ref="treeCityPicker"
      :multiple="true"
      @select-change="selectCityChange"
      title="选择城市"
      :localdata="cityListData"
      valueKey="id"
      textKey="name"
      childrenKey="children"
      :selectParent="false"
    />
    <TreePicker
      ref="treeCategoryPicker"
      :multiple="true"
      @select-change="selectCategoryChange"
      title="选择服务品类"
      :localdata="categoryListData"
      valueKey="id"
      textKey="value"
      childrenKey="children"
      :selectParent="false"
    />
    <u-loading-icon v-show="workerLoading"></u-loading-icon>
  </view>
</template>

<script>
import Step from "@/components/step/index";
import Upload from "@/components/upload/index";
import sfzIcon from "@/static/images/sfz-icon.png";
import sffIcon from "@/static/images/sff-icon.png";
import iconAdd from "@/static/images/icon-add.png";
import waitingReviewIcon from "@/static/images/waiting-review-icon.png";
import authenticationFailedIcon from "@/static/images/authentication-failed-icon.png";
import certificationSuccessfulIcon from "@/static/images/certification-successful-icon.png";
import TreePicker from "@/components/treePicker/index";
import { workerCreate, cityTree, codeTree, workerDetail } from "@/api/worker";
export default {
  components: { Step, Upload, TreePicker },
  data() {
    return {
      sfzIcon,
      sffIcon,
      iconAdd,
      waitingReviewIcon,
      authenticationFailedIcon,
      certificationSuccessfulIcon,
      current: 1,
      stepList: [
        {
          statusName: "身份认证",
        },
        {
          statusName: "设置服务",
        },
        {
          statusName: "资质审核",
        },
        {
          statusName: "完成",
        },
      ],
      showPopup: false,
      userInfo: {
        realName: "",
        phone: "",
        idCard: "",
      },
      // treeList
      cityListData: [],
      categoryListData: [],
      selectCityName: "",
      selectCityIds: [],
      selectCategoryName: "",
      selectCategoryIds: [],
      upLoadSfz: [], // 身份证正面
      upLoadSff: [], // 身份证反面
      workerAreaParams: [],
      workerCategoryParams: [],
      isInReview: true,
      isAuditFailed: false,
      rejectReason: "",
      workerLoading: false,
      rules: {},
    };
  },
  mounted() {
    this.cityTree();
    this.codeTree();
    this.workerDetail();
  },
  methods: {
    async workerDetail() {
      try {
        this.workerLoading = true;
        const res = await workerDetail();
        this.workerLoading = false;
        //REJECTED(0, "驳回"),APPROVED(1, "通过"),UNAUDITED(2, "未审核");
        const auditStatus = res.data.auditStatus;
        switch (auditStatus) {
          case 1:
            this.current = 4;
            const areaList = res.data.areaList;
            const categoryList = res.data.categoryList;
            const areaListData = [];
            const categoryListData = [];
            areaList.forEach((item) => {
              areaListData.push(item.areaId);
            });
            categoryList.forEach((item) => {
              categoryListData.push(item.categoryId);
            });
            uni.setStorageSync("areaId", JSON.stringify(areaListData));
            uni.setStorageSync("categoryId", JSON.stringify(categoryListData));
            break;
          case 2:
            this.current = 3;
            this.isInReview = true;
            this.isAuditFailed = false;
            break;
          case 0:
            this.current = 3;
            this.isInReview = false;
            this.isAuditFailed = true;
            this.rejectReason = res.data.rejectReason;
            break;
          default:
            this.current = 1;
            this.isInReview = true;
            this.isAuditFailed = false;
            break;
        }
      } catch (error) {
        this.workerLoading = false;
        console.log(error);
      }
    },
    async cityTree() {
      try {
        const res = await cityTree();
        this.cityListData = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    async codeTree() {
      try {
        const res = await codeTree();
        this.categoryListData = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 下一步
    async nextStep(value) {
      if (value === 2) {
        // 第一步输入验证
        if (this.userInfo.realName === "") {
          return wx.showToast({
            title: "请输入姓名",
            icon: "none",
            duration: 2000,
          });
        }
        if (this.userInfo.phone === "") {
          return wx.showToast({
            title: "请输入手机号",
            icon: "none",
            duration: 2000,
          });
        }
        if (this.userInfo.idCard === "") {
          return wx.showToast({
            title: "请输入身份证号码",
            icon: "none",
            duration: 2000,
          });
        }
        if (this.upLoadSfz.length <= 0) {
          return wx.showToast({
            title: "请上传身份证正面",
            icon: "none",
            duration: 2000,
          });
        }
        if (this.upLoadSff.length <= 0) {
          return wx.showToast({
            title: "请上传身份证反面",
            icon: "none",
            duration: 2000,
          });
        }
        this.current = value;
      }
      if (value === 3) {
        if (this.workerAreaParams.length <= 0) {
          return wx.showToast({
            title: "请选择服务区域",
            icon: "none",
            duration: 2000,
          });
        }
        if (this.workerCategoryParams.length <= 0) {
          return wx.showToast({
            title: "请选择服务品类",
            icon: "none",
            duration: 2000,
          });
        }
        try {
          const parmas = {
            attachList: [
              {
                id: this.upLoadSfz[0].id,
                type: 1,
                url: this.upLoadSfz[0].url,
              },
              {
                id: this.upLoadSff[0].id,
                type: 2,
                url: this.upLoadSff[0].url,
              },
            ],
            idCard: this.userInfo.idCard,
            phone: this.userInfo.phone,
            realName: this.userInfo.realName,
            workerAreaParams: this.workerAreaParams,
            workerCategoryParams: this.workerCategoryParams,
          };
          await workerCreate(parmas);
          this.current = value;
          this.isInReview = true;
        } catch (error) {
          wx.showToast({
            title: "入驻失败，请检查！",
            icon: "none",
            duration: 2000,
          });
          console.log(error);
        }
      }
    },
    // 上一步
    backStep(value) {
      this.current = value;
    },
    // 跳转到立即抢单
    immediateOrder() {
      uni.switchTab({
        url: "/pages/tabBar/seizeOrders/index",
      });
    },
    // 跳转首页
    linkStaging() {
      uni.switchTab({
        url: "/pages/tabBar/staging/index",
      });
    },
    // 再次申请
    reApply() {
      this.current = 1;
    },
    openPopup() {
      this.showPopup = true;
    },
    close() {
      this.showPopup = false;
    },
    // 显示城市选择器
    showCityPicker() {
      this.$refs.treeCityPicker._show();
    },
    // 显示服务品类选择器
    showCategoryPicker() {
      this.$refs.treeCategoryPicker._show();
    },
    //监听城市选择（ids为数组）
    selectCityChange(ids, names) {
      this.selectCityIds = ids;
      this.selectCityName = names;
      // 处理数据成为接口接口的数据格式
      const cityNames = this.selectCityName.split(" / ");
      const workerAreaParams = [];
      this.selectCityIds.map((item, index) => {
        workerAreaParams.push({
          areaId: item,
          areaDetail: cityNames[index],
        });
      });
      this.workerAreaParams = workerAreaParams;
    },
    //监听服务品类选择（ids为数组）
    selectCategoryChange(ids, names) {
      this.selectCategoryIds = ids;
      this.selectCategoryName = names;
      // 处理数据成为接口接口的数据格式
      const categoryNames = this.selectCategoryName.split(" / ");
      const workerCategoryParams = [];
      this.selectCategoryIds.map((item, index) => {
        workerCategoryParams.push({
          categoryId: item,
          categoryDetail: categoryNames[index],
        });
      });
      this.workerCategoryParams = workerCategoryParams;
    },
    // 获取身份证正面
    getUpLoadSfz(e) {
      this.upLoadSfz = e;
    },
    // 获取身份证反面
    getUpLoadSff(e) {
      this.upLoadSff = e;
    },
  },
};
</script>
<style lang="scss" scoped>
.worker-settlement {
  .form-container {
    background: #fff;
    .input-name {
      margin: 0 30rpx;
      border-bottom: 1rpx solid #eeeeee;
    }
    .last-name {
      border-bottom: none;
    }
  }
  .upload-container {
    margin: 32rpx;
    padding-bottom: 108rpx;
    ::v-deep {
      .u-upload__wrap {
        flex-direction: column;
        flex-wrap: nowrap;
      }
    }
    .upload-file {
      margin-bottom: 20rpx;
      .upload-file-pic {
        display: flex;
        align-items: center;
        position: relative;
        .infor-image {
          margin: 0 auto;
        }
        .title {
          position: absolute;
          width: 100%;
          text-align: center;
          bottom: 110rpx;
          font-size: 34rpx;
          font-family: Source Han Sans CN-Regular, Source Han Sans CN;
          font-weight: 400;
          color: #3d3d3d;
        }
      }
    }
  }
  .next-step {
    position: fixed;
    bottom: 20rpx;
    width: 100%;
    .btn {
      margin: 0 32rpx;
      height: 88rpx;
      background: #457ef6;
      border-radius: 12rpx 12rpx 12rpx 12rpx;
      font-size: 32rpx;
      font-family: Source Han Sans CN-Medium, Source Han Sans CN;
      font-weight: 500;
      color: #ffffff;
      line-height: 88rpx;
      text-align: center;
    }
  }
  .selection-service {
    background: #fff;
    margin-top: 30rpx;
    .service-list {
      border-bottom: 1rpx solid #eeeeee;
      display: flex;
      justify-content: space-between;
      padding: 20rpx 32rpx;
      .title {
        min-width: 150rpx;
        font-size: 30rpx;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
        font-weight: 400;
        color: #353535;
        line-height: 52rpx;
        flex: 1;
      }
      .select-list {
        font-size: 30rpx;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
        font-weight: 400;
        color: #999999;
        line-height: 52rpx;
      }
    }
  }
  .btn-container {
    position: fixed;
    bottom: 20rpx;
    width: 100%;
    .btn-list {
      display: flex;
      justify-content: space-between;
      .btn {
        width: 50%;
        margin: 0 32rpx;
        height: 88rpx;
        background: #457ef6;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
        font-size: 32rpx;
        font-family: Source Han Sans CN-Medium, Source Han Sans CN;
        font-weight: 500;
        color: #ffffff;
        line-height: 88rpx;
        text-align: center;
      }
    }
  }
  .status-image {
    .infor-image {
      display: flex;
      align-items: center;
      margin-top: 160rpx;
    }
    .status {
      font-size: 32rpx;
      font-family: Source Han Sans CN-Medium, Source Han Sans CN;
      font-weight: 500;
      color: #3d3d3d;
      line-height: 52rpx;
      text-align: center;
    }
    .tips {
      margin: 10rpx 32rpx;
      font-size: 30rpx;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #353535;
      line-height: 44rpx;
      text-align: center;
    }
  }
}
</style>